package com.itheima.axios;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Person;
import com.itheima.pojo.Student;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet(urlPatterns = "/Ajax3Servlet")
public class Ajax3Servlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 接收请求
        /*
         * TODO:
         *   参数格式有两种
         *   1). 传统url格式
         *           name=zs&age=18
         *           获取:
         *              String name = request.getParameter("name");
         *   2). json格式
         *           只能获得数据(json格式) : 掌握http协议
         *           将此数据封装到javabean : fastjson
         * */
//        request.setCharacterEncoding("utf-8");
        //获取请求体输入流
        // 因为前端是通过post请求提交参数,参数就在请求体中
       /* ServletInputStream is = request.getInputStream();
        int length;
        byte[] buffer = new byte[1024];
        while((length = is.read(buffer)) != -1){
            String str = new String(buffer, 0, length);
//            System.out.println(str);

            //json格式字符串 变成 javaBean
            Student student = JSON.parseObject(str, Student.class);
            System.out.println(student);
        }*/

       request.setCharacterEncoding("utf-8");
        ServletInputStream is = request.getInputStream();
        Student s = JSON.parseObject(is, Student.class);
        System.out.println(s);
        System.out.println("登陆成功");

        //2 业务处理

        //3响应数据
        ArrayList<Person> list = new ArrayList<>();
        Person p1 = new Person("高圆圆",18);
        Person p2 = new Person("李希铭",19);
        Person p3 = new Person("金佳茜",20);
        list.add(p1);
        list.add(p2);
        list.add(p3);
        String content = JSON.toJSONString(list);
        System.out.println(content);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print(content);
    }
}